import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Tools, List, Button } from 'weaver-mobile';
import { Form } from 'weaver-mobile-page';
import { renderLoading } from '../public';
const getLabel = Tools.getLabel;
@withRouter
@inject('communicationStore')
@observer
export default class CreateTag extends React.Component {
  static defaultProps = {
    prefixCls: 'cowork-communication-createTag',
  }

  constructor(props) {
    super(props);
    this.state={
      optType: '', //操作的类型
      labelType: 'label', // 标签类型（自定义:label;版块:typePlate）
      id: '', // 编辑的标签id
    }
  }

  componentDidMount() {
    const { communicationStore: { tagStore }, location: { pathname, state } } = this.props;
    const { coworkLabelCondition } = tagStore;
    if (pathname.indexOf('/createTag')>-1) {
      this.setState({optType: 'add'});
      coworkLabelCondition({operateType: 'add', id: ''}, pathname);
    }
    if (pathname.indexOf('/editTag')>-1){
      this.setState({optType: 'edit', id: (state && state.id) || ''});
      coworkLabelCondition({operateType: 'edit', id: (state && state.id) || ''}, pathname);
    } 
    // coworkLabelCondition({operateType: 'add', id: state && state.id || ''}, pathname);
    // if (pathname.indexOf('/createTag')>-1) this.setState({optType: 'add'});
    // if (pathname.indexOf('/editTag')>-1) this.setState({optType: 'edit'});
  }

  getFields = () => {
    const { communicationStore: { tagStore } } = this.props;
    const { tagForm } = tagStore;
    const { conditioninfo, isInit } = tagForm;
    const fields = [];
    if (isInit) {
      toJS(conditioninfo[0].items).map((item, index) => {
        fields.push(<Form.Item
          key={item.domkey.join('__')}
          form={tagForm}
          fieldConfig={item}
          onChange={tagForm.onChange}
				/>);
				return item;
      })
      return fields;
    }
  }

  render(){
    const { prefixCls, communicationStore: { tagStore, getSearchAdvancedCondition }, history } = this.props;
    const { newTagLoading, submitTag, createSaveLoading } = tagStore;
    const { optType, labelType,id } = this.state;
    return newTagLoading ? renderLoading : (
      <div className={prefixCls}>
        <Form>
          <List>{this.getFields()}</List>
        </Form>
        <Button 
          type="primary" 
          loading={createSaveLoading} 
          onClick={() => 
            submitTag(
              {operateType: optType,id:id,labelType: labelType},
              () => {
                getSearchAdvancedCondition();
                history.go(-1);
              }
          )}
        >{getLabel(30986,'保存')}</Button>
      </div>
    );
  }
}